package hn.cch.service.impl;

import hn.cch.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Boolean exists(String key){
        return redisTemplate.hasKey(key);
    }

    /**
     *
     * @param key
     * @param value
     * @param expire 过期时间（单位秒）
     */
    public void set(String key, String value, long expire){
        redisTemplate.opsForValue().set(key,value, expire, TimeUnit.SECONDS);
    }
    public void set(String key, String value){
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 没有找到key返回key为null
     * @param key
     * @return
     */
    public String get(String key){
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))){
            return (String) redisTemplate.opsForValue().get(key);
        }
        return null;
    }

}
